package com.xiaohe.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xiaohe.gulimall.product.entity.CategoryBrandRelationEntity;
import com.xiaohe.gulimall.product.service.CategoryBrandRelationService;
import com.xiaohe.gulimall.product.vo.Catelog2Vo;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaohe.common.utils.PageUtils;
import com.xiaohe.common.utils.Query;

import com.xiaohe.gulimall.product.dao.CategoryDao;
import com.xiaohe.gulimall.product.entity.CategoryEntity;
import com.xiaohe.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    //查询所有分类
    @Override
    public List<CategoryEntity> listWithTree() {
        //查出所有的分类
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);

        //找出所有的一级分类，父分类id为0
        List<CategoryEntity> level1 = categoryEntities.stream().filter((categoryEntity ->
             categoryEntity.getParentCid() == 0
        )).map((menu)->{
            menu.setChildren(getChildren(menu,categoryEntities));
            return menu;
        }).sorted((menu1,menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
        return level1;
    }

    /**
     * 自定义删除功能
     * @param ids
     */
    @Override
    public void removeMenusByIds(List<Long> ids) {
        //TODO 检查当前删除的菜单，是否被其他别的地方引用
        baseMapper.deleteBatchIds(ids);
    }

    //找到catelog的全路径
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths =new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId,paths);
        //逆序
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    /**
     * 级联更新所有关联的数据
     * @param category
     */
    @CacheEvict(value="category",allEntries = true)
    @Override
    @Transactional
    public void updateDetail(CategoryEntity category) {
        //添加读写锁
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("catalogJson-lock");
        //创建写锁
        RLock rLock = readWriteLock.writeLock();
        try {
            rLock.lock();
            this.baseMapper.updateById(category);
            categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            rLock.unlock();
        }


    }

    private List<Long> findParentPath(Long catelogId,List<Long> paths){
        //收集当前节点id
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if(byId.getParentCid()!=0){
            findParentPath(byId.getParentCid(),paths);
        }
        return paths;
    }
    private List<CategoryEntity> getChildren(CategoryEntity root,List<CategoryEntity> all){
        List<CategoryEntity> children = all.stream().filter((item) ->
            root.getCatId() == item.getParentCid()
        ).map(categoryEntity -> {
            categoryEntity.setChildren(getChildren(categoryEntity,all));
            return categoryEntity;
        }).sorted((menu1,menu2)->{
            return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }


    //查询所有的一级分类
    @Cacheable(value = {"category"},key = "#root.method.name",sync = true)//sync = true加锁
    @Override
    public List<CategoryEntity> getLevel1Category() {
        QueryWrapper<CategoryEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_cid",0);
        List<CategoryEntity> categoryEntities = this.baseMapper.selectList(wrapper);
        return categoryEntities;
    }
    @Override
    //每一个需要缓存的数据，都来指定要放到那个名字的分区
    @Cacheable(value = "category",key = "#root.method.name")
    public Map<String, List<Catelog2Vo>>  getCatalogJson() {

        Map<String, List<Catelog2Vo>> catalogJsonFromDb = getCatalogJsonFromDb();
        //给缓存中放json字符串，拿出的json字符串，还要用逆转为能用的对象内类型
        //1、加入缓存
        /**
         * 1、空结果缓存：解决缓存穿透
         * 2、设置过期时间（附加随机值）：解决缓存雪崩
         * 3、加锁：解决缓存击穿
         */
        /*String catalogJson = redisTemplate.opsForValue().get("catalogJson");
        if(StringUtils.isEmpty(catalogJson)){
            //2、缓存没有查询数据库
            Map<String, List<Catelog2Vo>> catalogJsonFromDb = getCatalogJsonFromDb();
            //3、查到的数据保存在数据库
            String jsonString = JSON.toJSONString(catalogJsonFromDb);
            redisTemplate.opsForValue().set("catalogJson",jsonString,1, TimeUnit.DAYS);
            //返回查询数据库的信息
            return catalogJsonFromDb;
        }
        //转为我们指定的对象
        Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJson,new TypeReference<Map<String, List<Catelog2Vo>>>(){});*/
        return catalogJsonFromDb;
    }


    //前台，分类
    //从数据库查询并且封装
    public Map<String, List<Catelog2Vo>>  getCatalogJsonFromDb() {
        //查询所有分类
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        //所有一级分类
        List<CategoryEntity> level1Category = getParentCid(selectList,0L);
        //封装数据
        Map<String, List<Catelog2Vo>> parent_cid = level1Category.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //遍历每一个一级分类
            //查到一级分类的所有二级分类
            //每一个的一级分类，查到这个一级分类的二级分类
            List<CategoryEntity> categoryEntities = getParentCid(selectList,v.getCatId());
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                //封装上面的结果
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //找当前二级分类的三级分类
                    List<CategoryEntity> level3Catelog = getParentCid(selectList,l2.getCatId());
                    if(level3Catelog!=null){
                        List<Catelog2Vo.Catelog3Vo> collect = level3Catelog.stream().map(l3 -> {
                            //封装指定的数据
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        //将三级放到2级
                        catelog2Vo.setCatalog3List(collect);
                    }
                    return catelog2Vo;

                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        return parent_cid;
    }

    //抽取公共方法
    private List<CategoryEntity> getParentCid(List<CategoryEntity> selectList,Long parent_cid) {
        List<CategoryEntity> collect = selectList.stream().filter(item -> item.getParentCid() == parent_cid
        ).collect(Collectors.toList());
        return collect;
    }
}